import os
import sys
import argparse
from pathlib import Path
from typing import Optional
try:
    import pymupdf  # PyMuPDF for PDF processing
except ImportError:
    print("Error: PyMuPDF is not installed. Please install dependencies as per the README.")
    sys.exit(1)


try:
    from tqdm import tqdm
except ImportError:
    tqdm = None  # Progress bar is optional

def convert_pdf_to_images(pdf_path: str, output_dir: Optional[str] = None, fmt: str = 'png'):
    pdf_file = Path(pdf_path)
    if not pdf_file.exists() or not pdf_file.is_file():
        print(f"Error: File '{pdf_path}' does not exist or is not a file.")
        return False
    if pdf_file.suffix.lower() != '.pdf':
        print(f"Error: File '{pdf_path}' is not a PDF.")
        return False
    pdf_name = pdf_file.stem
    out_dir = Path(output_dir) if output_dir else pdf_file.parent / pdf_name
    out_dir.mkdir(parents=True, exist_ok=True)

    try:
        # Open PDF document with PyMuPDF
        doc = pymupdf.open(str(pdf_file))
    except Exception as e:
        print(f"Error: Failed to open PDF '{pdf_path}': {e}")
        return False

    total_pages = doc.page_count
    if total_pages == 0:
        print(f"Error: PDF '{pdf_path}' contains no pages.")
        doc.close()
        return False

    bar = tqdm(total=total_pages, desc="Converting", unit="page") if tqdm else None

    for page_num in range(total_pages):
        try:
            # Load the page
            page = doc.load_page(page_num)

            # Create pixmap (image) from page
            # Using default resolution (96 DPI) to match pdf2image behavior
            pix = page.get_pixmap()

            # Generate output filename
            img_name = f"{page_num + 1:03d}_{pdf_name}.{fmt}"
            img_path = out_dir / img_name

            # Save the image
            if fmt.lower() == 'jpeg':
                pix.save(str(img_path), output="jpeg")
            else:  # Default to PNG
                pix.save(str(img_path), output="png")

            # Clean up pixmap
            pix = None

        except Exception as e:
            print(f"Error: Failed to convert page {page_num + 1}: {e}")
            continue

        if bar:
            bar.update(1)

    # Clean up
    doc.close()
    if bar:
        bar.close()

    print(f"Done. Images saved to: {out_dir}")
    return True

def main():
    parser = argparse.ArgumentParser(description="Convert PDF pages to images.")
    parser.add_argument('pdf', help='Path to the PDF file to convert')
    parser.add_argument('-o', '--output', help='Output directory (default: <pdf_name> in same folder)', default=None)
    parser.add_argument('-f', '--format', help='Image format: png or jpeg (default: png)', choices=['png', 'jpeg'], default='png')
    args = parser.parse_args()
    success = convert_pdf_to_images(args.pdf, args.output, args.format)
    if not success:
        sys.exit(1)

if __name__ == '__main__':
    main() 